package com.mlnx.bluwifi.sampleTool;

import com.alibaba.fastjson.JSONObject;
import com.mlnx.bluwifi.pojo.dto.SampleEntity;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * 将采样数据输出到外部文件
 *
 * @author zzb
 * @create 2020/3/9 13:26
 */
public class SampleTool {

    public static void main(String[] args) {

        InputStream in = null;
        try {
            System.out.println("ap mac:{} 开始接收蓝牙数据");
            URL url = new URL("http://192.168.1.89/gap/rssi?rssi_interval=100");
            URLConnection connection = url.openConnection();
            connection.setReadTimeout(5000);
            in = connection.getInputStream();  //带资源的try-catch语句。自动关闭
            InputStream buffer = new BufferedInputStream(in);

            //将InputStream串链到一个Reader
            Reader reader = new InputStreamReader(buffer);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = "";
            Long time = System.currentTimeMillis();
            FileWriter fw = new FileWriter(new File("D:\\蓝牙行走测样\\连续行走全程无遮挡测样.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            int i = 1;
            while (true) {
                str = bufferedReader.readLine();
                if (!((":keep-alive").equals(str) || str.length() == 0)) {
                    String spoValue = str.substring(5);
                    SampleEntity sampleEntity = JSONObject.parseObject(spoValue, SampleEntity.class);
                    System.out.println(sampleEntity.getRssi());
                    i++;
                    if (i % 10 == 0) {
                        bw.write(sampleEntity.getRssi());
                        bw.newLine();
                        bw.write("=================================");
                        bw.newLine();
                    } else {
                        bw.write(sampleEntity.getRssi());
                        bw.newLine();
                    }

                    if ((System.currentTimeMillis() - time) > 10000) {
                        bw.close();
                    }
                }
            }
        } catch (Exception e) {
            if (!("Connection timed out: connect".equals(e.getMessage()) || "Read timed out".equals(e.getMessage()))) {

            }

        } finally {
            if (in != null) {
                try {
                    in.close();

                } catch (IOException e) {

                }
            }
        }

    }

}
